﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace CompositionPlugin.Service
{
    public class Log : ILog, IModuleRuntimeServiceGenerator
    {
        public const int DefaultEventID = 0;

        public Log()
        {
            // init
            this.ChildLogs = new ReadOnlyObservableCollection<ModuleLog>(this._childLogs);
            // config
            if (SystemRuntime.Current.Configuration.Log.RuntimeLogWatcherEnabled)
            {
                // add stream watcher
            }
        }

        public virtual void Initialize() { }

        public void Write(TraceEventType eventType, int id, string message)
        {
            _traceSource.TraceEvent(eventType, id, message);
        }

        public IRuntimeService GetModuleRuntimeService(ModuleDefinition definition, out Type contractType)
        {
            contractType = typeof(IModuleLog);
            TraceSource traceSource = new TraceSource(definition.Metadata.Name, _traceSource.Switch.Level);
            var childLog = new ModuleLog(this, traceSource);
            this.AttachChildLog(childLog);
            return childLog;
        }

        public virtual void OnRuntimeDisposing() { }

        public ReadOnlyObservableCollection<ModuleLog> ChildLogs { get; private set; }

        #region internal

        internal void AttachChildLog(ModuleLog childLog)
        {
            lock (this)
            {
                if (!this._childLogs.Contains(childLog))
                    this._childLogs.Add(childLog);
            }
        }

        internal void DetachChildLog(ModuleLog childLog)
        {
            lock (this)
            {
                if (this._childLogs.Contains(childLog))
                    this._childLogs.Remove(childLog);
            }
        }

        #endregion

        #region private

        private readonly static TraceSource _traceSource = new TraceSource("default");

        private readonly ObservableCollection<ModuleLog> _childLogs = new ObservableCollection<ModuleLog>();

        #endregion
    }
}
